package com.ufo.store.management.ui.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Isszmbalv3Member;
import com.ufo.store.management.utils.DialogUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.view.FloatTextToast;
import com.ufo.store.management.widget.dialog.ProtogenesisInputDialog;

import java.text.SimpleDateFormat;

/**
 * Created by taoli on 2017/12/29.
 */

public class Isszmbalv3MemberEditFragment extends Fragment{
    private LinearLayout mRootLayout = null;
    private EditText mMemberIdEt = null;
    private EditText mMemberNameEt = null;
    private EditText mMemberSexEt = null;
    private EditText mMemberMobileEt = null;
    private EditText mMemberTypeEt = null;
    private EditText mMemberCardNoEt = null;
    private EditText mMemberAccNumEt = null;
    private EditText mMemberNowAccNumEt = null;
    private EditText mMemberTotalConsumeAmtEt = null;
    private EditText mMemberTotalConsumeCountEt = null;

    private Isszmbalv3Member mIsszmbalv3MemberInfo = null;
    private boolean mbIsInsertData = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootLayout = (LinearLayout) inflater.inflate(R.layout.fragment_isszambalv3_member_edit, container, false);
        mbIsInsertData = getArguments().getBoolean("IsInsertData");
        mIsszmbalv3MemberInfo = (Isszmbalv3Member) getArguments().getSerializable("Isszmbalv3MemberInfo");
        initialize(mRootLayout);
        initData();
        return mRootLayout;
    }

    private void initialize(View rootView){
        mMemberIdEt = (EditText) rootView.findViewById(R.id.member_id_et);
        mMemberNameEt = (EditText) rootView.findViewById(R.id.member_name_et);
        mMemberSexEt = (EditText) rootView.findViewById(R.id.member_sex_et);
        mMemberMobileEt = (EditText) rootView.findViewById(R.id.member_mobile_et);
        mMemberTypeEt = (EditText) rootView.findViewById(R.id.member_type_et);
        mMemberCardNoEt = (EditText) rootView.findViewById(R.id.member_cardno_et);
        mMemberAccNumEt = (EditText) rootView.findViewById(R.id.member_acc_num_et);
        mMemberNowAccNumEt  = (EditText) rootView.findViewById(R.id.member_now_acc_num_et);
        mMemberTotalConsumeAmtEt = (EditText) rootView.findViewById(R.id.member_totalconsume_amt_et);
        mMemberTotalConsumeCountEt = (EditText) rootView.findViewById(R.id.member_totalconsume_count_et);

        mMemberIdEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mMemberCardNoEt.setText(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        if (mIsszmbalv3MemberInfo != null) {
            mMemberIdEt.setText(mIsszmbalv3MemberInfo.memberCardId);
            mMemberCardNoEt.setText(mIsszmbalv3MemberInfo.memberCardNo);
            mMemberNameEt.setText(mIsszmbalv3MemberInfo.memberName);
            mMemberSexEt.setText(mIsszmbalv3MemberInfo.memberSex);
            if( !TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberMobile))
                mMemberMobileEt.setText(mIsszmbalv3MemberInfo.memberMobile);
            else if( !TextUtils.isEmpty(mIsszmbalv3MemberInfo.memberTel))
                mMemberMobileEt.setText(mIsszmbalv3MemberInfo.memberTel);
            if( mIsszmbalv3MemberInfo.memberCardType.trim().equals("0")){
                mMemberTypeEt.setText("会员卡");
            }else if(mIsszmbalv3MemberInfo.memberCardType.trim().equals("1")){
                mMemberTypeEt.setText("折扣卡");
            }
            mMemberAccNumEt.setText(String.valueOf(mIsszmbalv3MemberInfo.memberAccNum));
            mMemberNowAccNumEt.setText(String.valueOf(mIsszmbalv3MemberInfo.memberAccNum - mIsszmbalv3MemberInfo.memberDecNum));
            mMemberTotalConsumeAmtEt.setText(String.valueOf(mIsszmbalv3MemberInfo.memberConsumAmt) + "元");
            mMemberTotalConsumeCountEt.setText(String.valueOf(mIsszmbalv3MemberInfo.memberConsumCount));
        }
    }

    private void initData(){

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl1:
            case R.id.member_id_et:
                new ProtogenesisInputDialog(getActivity(), mMemberIdEt, "会员序号、卡号", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberIdEt.setText(inputString);
                        mMemberCardNoEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl2:
            case R.id.member_name_et:
                new ProtogenesisInputDialog(getActivity(), mMemberNameEt, "会员姓名", null).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberNameEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl3:
            case R.id.member_sex_et:
                pickSex();
                break;
            case R.id.rl4:
            case R.id.member_mobile_et:
                new ProtogenesisInputDialog(getActivity(), mMemberMobileEt, "手机", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberMobileEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl5:
            case R.id.member_type_et:
                pickCard();
                break;
            case R.id.rl6:
            case R.id.member_cardno_et:
                new ProtogenesisInputDialog(getActivity(), mMemberCardNoEt, "卡号", new DigitsKeyListener(false, false)).setItemClickListener(new ProtogenesisInputDialog.OnItemClick() {
                    @Override
                    public void onPositiveButtonClick(String inputString) {
                        mMemberCardNoEt.setText(inputString);
                    }

                    @Override
                    public void onNegativeButtonClick() {

                    }
                });
                break;
            case R.id.rl7:
            case R.id.member_acc_num_et:

                break;
            case R.id.rl8:
            case R.id.member_now_acc_num_et:

                break;
            case R.id.rl9:
            case R.id.member_totalconsume_amt_et:

                break;
            case R.id.rl10:
            case R.id.member_totalconsume_count_et:

                break;
        }
    }

    public void submitIsszmbalv3MemberEdit() {
        String memberIdEtStr = mMemberIdEt.getText().toString();
        String memberNameEtStr = mMemberNameEt.getText().toString();
        String memberSexEtStr = mMemberSexEt.getText().toString();
        String memberMobileEtStr = mMemberMobileEt.getText().toString();
        String memberCardNoEtStr = mMemberCardNoEt.getText().toString();
        String nulltakeplace = null;

        if (memberIdEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberIdEt, "会员ID不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberNameEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberNameEt, "会员姓名不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberMobileEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberMobileEt, "会员电话不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }
        if (memberCardNoEtStr.length() == 0) {
            FloatTextToast.makeText(getActivity(), mMemberCardNoEt, "会员卡号不能为空！", FloatTextToast.LENGTH_SHORT).show();
            return;
        }


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String memberVipStartdayStr = format.format(mIsszmbalv3MemberInfo.memberVipStartDay);
        String memberVipEnddayStr = format.format(mIsszmbalv3MemberInfo.memberVipEndDay);
        String memberSavStartdayStr = format.format(mIsszmbalv3MemberInfo.memberSavStartDay);
        String memberSavEnddayStr = format.format(mIsszmbalv3MemberInfo.memberSavEndDay);
        try {
            java.util.Date date = format.parse(memberVipEnddayStr);
            date.setYear( date.getYear() + 50 );
            memberVipEnddayStr = format.format(date);
            date = format.parse(memberSavEnddayStr);
            date.setYear( date.getYear() + 50 );
            memberSavEnddayStr = format.format(date);
        } catch (Exception e) {
            return;
        }

        try {
            ContentValues initialValues = new ContentValues();
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_id, memberIdEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_no, memberCardNoEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_type, mIsszmbalv3MemberInfo.memberCardType);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_name, memberNameEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_rem, Utils.cn2FirstSpell(memberNameEtStr));
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_sex, memberSexEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_tel, memberMobileEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_email, mIsszmbalv3MemberInfo.memberEmail);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_mobile, memberMobileEtStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_start_date, memberVipStartdayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_end_date, memberVipEnddayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_sav_start_date, memberSavStartdayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_sav_end_date, memberSavEnddayStr);

            //以下字段当新建时不允许空值
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_oper_id, "1001");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_oper_date, memberVipStartdayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_send_amt, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_vip_tax, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_card_status, "0");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_use_num, 9999999);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_save_amt, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_residual_amt, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_consum_amt, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_consum_count, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_now_acc_num, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_acc_num, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_dec_num, 0);

            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_marriage, "未婚");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_nation, "汉");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_modify_date, memberVipStartdayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_item_amt, 0);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_branch_no, "000001");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_bth_flag, "公历");
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_oper_date_gi, memberVipStartdayStr);
            initialValues.put(DatabaseManager.ISSZMBALV3_t_rm_vip_oper_id_gi, "1001");
            new SubmitIsszmbalv3MemberInfoTask().execute(initialValues);
        } catch (Exception e) {
            return;
        }
    }

    private class SubmitIsszmbalv3MemberInfoTask extends AsyncTask<ContentValues, Void, String> {
        public SubmitIsszmbalv3MemberInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showWaitDialog("正在处理，请稍等...");
        }

        @Override
        protected String doInBackground(ContentValues... params) {
            if (getActivity().isFinishing()) {
                return "";
            }
            final ContentValues initialValues = params[0];
            long row = -1;
            if( BarApplication.getInstance().mDatabaseIsSqlServer) {
                if (mbIsInsertData)
                    row = DatabaseManager.insertIsszmbalv3MemberInfoFromSqlServer(getActivity(), initialValues);
                else {
                    //DatabaseManager.deleteIsszmbalv3MemberInfoFromSqlServer(getActivity(), (String) initialValues.get(DatabaseManager.ISSZMBALV3_t_rm_vip_card_id));
                   // try {
                   //     Thread.sleep(1000);
                   // } catch (Exception e) {
                    //    e.printStackTrace();
                    //}
                    //row = DatabaseManager.insertIsszmbalv3MemberInfoFromSqlServer(getActivity(), initialValues);
                    row = DatabaseManager.replaceIsszmbalv3MemberInfoFromSqlServer(getActivity(), initialValues);
                }
            }
            //插入历史记录
            DatabaseManager.insertIsszmbalv3MemberInfoFromHistory(getActivity(), initialValues);

            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }
            hideWaitDialog();
            if (result.contains("-1")) {
                if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                    showTipsDialog("对不起，信息修改失败。");
                } else if(mOnProcessListener!=null){
                    mOnProcessListener.onProcessFinish(mMemberIdEt.getText().toString());
                }
            }else {
                if(mOnProcessListener!=null){
                    mOnProcessListener.onProcessFinish(mMemberIdEt.getText().toString());
                }
                getActivity().setResult(Activity.RESULT_OK);
                showTipsDialog("恭喜，成功修改了" + result + "条数据。");
            }
        }
    }

    private void showWaitDialog(final String tips) {
        DialogUtil.showWaitDialog(getActivity(), tips);
    }

    private void hideWaitDialog(){
        DialogUtil.hideWaitDialog();
    }

    public void showTipsDialog(final String tips) {
        DialogUtil.showTipsDialog(getActivity(), tips, new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    private void pickSex() {
        final String[] items = new String[] { "男", "女" };
        int index = 1;
        if(mMemberSexEt.getText().toString().equals("男")) {
            index = 0;
        }
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("性别")
                .setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mMemberSexEt.setText("男");
                        } else if (which == 1) {
                            mMemberSexEt.setText("女");
                        }
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private void pickCard() {
        final String[] items = new String[] { "会员卡", "折扣卡" };
        int index = 1;
        if(mMemberTypeEt.getText().toString().equals("会员卡")) {
            index = 0;
        }
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("卡类型")
                .setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mMemberTypeEt.setText("会员卡");
                            mIsszmbalv3MemberInfo.memberCardType = "0";
                        } else if (which == 1) {
                            mMemberTypeEt.setText("折扣卡");
                            mIsszmbalv3MemberInfo.memberCardType = "1";
                        }
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.getWindow().setWindowAnimations(R.style.dialog_anim_center_style);
        alertDialog.show();
    }

    private OnProcessListener mOnProcessListener = null;

    public void setOnProcessListener(OnProcessListener l) {
        mOnProcessListener = l;
    }

    public interface OnProcessListener {
        public void onProcessFinish(String memberId);
    }
}

